import os
from PIL import Image

import os
from PIL import Image

def split_image(image_path, output_dir, index):
    # 打开图像
    img = Image.open(image_path)
    
    # 获取图像的宽度和高度
    img_width, img_height = img.size
    
    # 计算每块小图的宽度和高度
    tile_width = img_width // 4
    tile_height = img_height // 4
    
    # 为当前图片创建一个以 camN 命名的文件夹
    cam_folder = os.path.join(output_dir, f"cam{index}")
    if not os.path.exists(cam_folder):
        os.makedirs(cam_folder)
    
    # 遍历 4x4 格子的每个区域，并保存为新的图像
    tile_index = 1
    for i in range(4):
        for j in range(4):
            # 计算每个小图的区域
            left = j * tile_width
            top = i * tile_height
            right = (j + 1) * tile_width
            bottom = (i + 1) * tile_height
            
            # 截取小图
            tile = img.crop((left, top, right, bottom))
            
            # 保存小图到对应的 camN 文件夹中
            tile.save(f"{cam_folder}/tile_{tile_index}.jpg")
            print(f"保存：{cam_folder}/tile_{tile_index}.jpg")
            tile_index += 1

def process_folder(input_folder, output_folder):
    # 获取文件夹中所有 .jpg 文件
    image_files = [f for f in os.listdir(input_folder) if f.lower().endswith('.jpg')]
    
    # 处理每个图片文件
    image_index = 1
    for image_file in image_files:
        image_path = os.path.join(input_folder, image_file)
        split_image(image_path, output_folder, image_index)
        # 更新索引
        image_index += 1

# 设置输入文件夹和输出文件夹
input_folder = "C:\\WorkOut\\Code\\3DGS\\Data\\MinorCity\\inputs\\images\\cam1"  # 替换为实际文件夹路径
output_folder = "C:\\WorkOut\\Code\\3DGS\\Data\\MinorCity\\inputs\\images\\camSeg"  # 替换为实际输出路径

# 处理文件夹中的所有图片
process_folder(input_folder, output_folder)
